/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.zrnecko.bowlingnumbers.session;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import net.zrnecko.bowlingnumbers.entity.FrameGame;
import net.zrnecko.bowlingnumbers.entity.Game;
import net.zrnecko.bowlingnumbers.entity.GameDetailLevel;
import net.zrnecko.bowlingnumbers.entity.PinGame;
import net.zrnecko.bowlingnumbers.entity.ResultGame;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

/**
 *
 * @author zrnecko
 */
@Stateful
@Scope(ScopeType.CONVERSATION)
@Name("newGameWizard")
public class NewGameWizardBean implements NewGameWizard {

	@Logger
	private static Log log;

	@PersistenceContext
	EntityManager em;

	@In
	FacesMessages facesMessages;

	private GameDetailLevel gameDetailLevel = GameDetailLevel.RESULT;

	private Game game;

	private int resultToVerify;

	@Begin(join=true)
	public String chooseDetailLevel() {
		String view = "";
		switch (gameDetailLevel)  {
			case RESULT: 
				log.debug("Detail level set to RESULT");
				game = new ResultGame();
				view = "newResultGame";
				break;
			case FRAME:
				log.debug("Detail level set to FRAME");
				game = new FrameGame();
				view = "newFrameGame";
				break;
			case PIN:
				log.debug("Detail level set to PIN");
				game = new PinGame();
				view = "newPinGame";
				break;
		}
		log.debug("View set to " + view);
		return view;
	}

	@End
	public String saveGame() {
		if (gameDetailLevel.equals(GameDetailLevel.RESULT)) {
			em.persist(game);
			return "gameSaved";
		} else {
			if (getResultToVerify() == game.getResult()) {
				em.persist(game);
				this.resultToVerify = 0;
				return "gameSaved";
			} else {
				facesMessages.add("Computed game result is #{newGameWizard.game.result} while provided #{newGameWizard.resultToVerify}! Check the game details!");
				return null;
			}
		}
	}

	@Remove
	@Destroy
	public void destroy() {

	}


	public GameDetailLevel getGameDetailLevel() {
		return gameDetailLevel;
	}

	public void setGameDetailLevel(GameDetailLevel gameDetailLevel) {
		this.gameDetailLevel = gameDetailLevel;
	}

	public Game getGame() {
		return game;
	}

	public void setGame(Game game) {
		this.game = game;
	}

	public int getResultToVerify() {
		return resultToVerify;
	}

	public void setResultToVerify(int resultToVerify) {
		this.resultToVerify = resultToVerify;
	}

}